package cn.tedu.mintmall.service.impl;

import cn.tedu.mintmall.dto.AddressAddNewDTO;
import cn.tedu.mintmall.dto.AddressUpdateDTO;
import cn.tedu.mintmall.entity.Address;
import cn.tedu.mintmall.exception.MintmallServiceException;
import cn.tedu.mintmall.mapper.AddressMapper;
import cn.tedu.mintmall.restful.ResponseCode;
import cn.tedu.mintmall.service.IAddressService;
import cn.tedu.mintmall.vo.AddressVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@Slf4j
public class AddressServiceImpl implements IAddressService {

    @Autowired
    private AddressMapper addressMapper;
    //1. 新增地址
    @Override
    public void addAddress(AddressAddNewDTO addressAddNewDTO) {
        Address address = new Address();
        BeanUtils.copyProperties(addressAddNewDTO,address);
        Long userId = 0L;
        LocalDateTime gmtCreate = LocalDateTime.now();
        LocalDateTime gmtModified = LocalDateTime.now();
        address.setUserId(userId);
        address.setGmtCreate(gmtCreate);
        address.setGmtModified(gmtModified);
        int rows = addressMapper.insertAddress(address);
        if (rows != 1){
            throw new MintmallServiceException(ResponseCode.INTERNAL_SERVER_ERROR, "新增地址失败! 系统忙, 请稍后再试!");
        }
        log.info("新增地址成功: {}", address);
    }

    //2. 删除地址通过用户id
    @Override
    public void removeAddress(Long userId) {
        int rows = addressMapper.deleteAddress(userId);
        if (rows != 1){
            throw new MintmallServiceException(ResponseCode.BAD_REQUEST, "删除地址失败! 请稍后再试!");
        }
        log.info("删除地址成功!");
    }

    //3. 根据联系人修改地址
    @Override
    public void updateAddress(AddressUpdateDTO addressUpdateDTO) {
        int rows = addressMapper.updateAddress(addressUpdateDTO);
        if (rows != 1){
            throw new MintmallServiceException(ResponseCode.BAD_REQUEST, "修改地址失败! 请稍后再试!");
        }
        log.info("修改地址成功:{}", addressUpdateDTO);
    }

    //4. 根据联系人查看地址
    @Override
    public AddressVO findAddressByContactName(String contactName) {
        AddressVO addressVO = addressMapper.selectAddressByContactName(contactName);
        if (addressVO == null){
            throw new MintmallServiceException(ResponseCode.BAD_REQUEST, "查询地址失败! 请检查联系人, 稍后再试!");
        }
        return addressVO;
    }

}
